package com.dhcc.httpserver;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;

import com.dhcc.util.CloseUtil;
import com.dhcc.util.Space;

/**
 * 封住响应信息
 * 
 * @author Administrator
 *
 */
public class Response {

	private StringBuilder headInfo;
	private int len;
	private StringBuilder content;
	
	private BufferedWriter bw;

	public Response() {

		headInfo = new StringBuilder();
		this.len = 0;

		this.content = new StringBuilder();
	}
	public Response(OutputStream os) {

		this();
		bw = new BufferedWriter(new OutputStreamWriter(os));
	}
	
	public Response(Socket client){

		this();
		try {
			bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
		} catch (IOException e) {
			
			this.headInfo=null;
		}
	}

	private void createHeader(int code) {

		// 响应头

		// 1) HTTP协版本、状态码、描述
		headInfo.append("HTTP/1.1").append(Space.BLANK);

		switch (code) {
		case 200:
			headInfo.append(200).append("OK");
			break;
		case 404:
			headInfo.append(404).append("NO FOUND");
			break;
		case 500:
			headInfo.append(500).append(Space.BLANK).append("SERVER ERROR");
			break;

		default:
			break;
		}

		headInfo.append(Space.CRLF);

		headInfo.append("Server:zkr Server/0.0.1").append(Space.BLANK).append(Space.CRLF);

		headInfo.append("Date:").append(Space.BLANK).append(new Date()).append(Space.CRLF);

		// 正文类型
		headInfo.append("Content-Type: text/html;charset=utf-8").append(Space.CRLF);
		// 正文长度：字节长度
		// headInfo.append("Content-Length:").append(Space.BLANK).append(responseContext.toString().getBytes().length)
		// .append(Space.CRLF);
		// 在正文之前有一个空行
		headInfo.append(Space.CRLF);

		

	}

	/**
	 * 构建正文
	 * 
	 * @param info 正文内容
	 */
	public Response print(String info) {

		content.append(info);

		return this;
	}

	/**
	 * 构建正文+回车
	 * @param info 正文内容
	 * @return Respose 这个响应对象
	 */
	public Response println(String info) {

		content.append(info).append(Space.CRLF);
		len +=(info+Space.CRLF).getBytes().length;

		return this;
	}
	
	void pushToClient(int code) throws IOException{
		
		if (null==headInfo) {
			code = 500;
		}
		
		createHeader(code);
		
		bw.append(headInfo.toString());
		
		bw.append(content.toString());
		bw.flush();
		
	}
	
	public void close() throws IOException{
		
		CloseUtil.closeAll(bw);
	}

}
